package filters;

import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import utils.BadWords;

public class ResponseWrapper extends HttpServletResponseWrapper {
	private PrintWriter  printWriter ;
	private CharArrayWriter  bufferedWriter;
	 ByteServletOutputStream servletOutputStream;  
	public ResponseWrapper(HttpServletResponse response) throws IOException {
		super(response);
		bufferedWriter = new CharArrayWriter();
		printWriter = new PrintWriter(bufferedWriter);
	}
	
	   public  ResponseWrapper(HttpServletResponse response, ByteArrayOutputStream buffer) {  
           super (response);  
           servletOutputStream = new  ByteServletOutputStream(buffer);  
       }  
	
	//覆盖getWriter()方法，使用我们自己定义的Writer   通过writer方式输出用这个    
//    public PrintWriter getWriter() throws IOException { 
//        return printWriter;      
//    }  
    
    public  PrintWriter getWriter()  throws  IOException {  
        if (printWriter ==  null ) {  
            printWriter = new  PrintWriter(servletOutputStream);  
        }  
        return  printWriter;  
    }  

    public   void  flushBuffer()  throws  IOException {  
        servletOutputStream.flush();  
        if (printWriter !=  null ) {  
            printWriter.flush();  
        }  
    }  
    
    private   static   class  ByteServletOutputStream  extends  ServletOutputStream {  
    	  
        ByteArrayOutputStream baos;  
  
        public  ByteServletOutputStream(ByteArrayOutputStream baos) {  
            super ();  
            this .baos = baos;  
        }  
  
        public   void  write( int  b)  throws  IOException {  
            baos.write(b);  
        }  
    }  
    //返回过滤敏感字后的响应字符串，
    public String getResult(){
    	return BadWords.filterBadWords(bufferedWriter.toString());
    }
    
  
    
}
